package com.chinaoly.sdk.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class OlyHttp {

    private volatile static OlyHttp INSTANCE = null;

    private OkHttpClient okHttpClient;
    private Retrofit retrofit;
    private int timeReadOut = 25;
    private int timeConnOut = 25;
    private String baseUrl = "http";
    private Interceptor[] muiltUrl;

    private OlyHttp() {
        //默认的配置项


    }


    public static OlyHttp newInstance() {
        if (INSTANCE == null) {
            synchronized (OlyHttp.class) {
                if (INSTANCE == null) {
                    INSTANCE = new OlyHttp();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 读取超时
     *
     * @param timeReadOut
     * @return
     */
    public OlyHttp setTimeReadOut(int timeReadOut) {
        this.timeReadOut = timeReadOut;
        return this;
    }

    /**
     * 连接超时
     *
     * @param timeConnOut
     * @return
     */
    public OlyHttp setTimeConnOut(int timeConnOut) {
        this.timeConnOut = timeConnOut;
        return this;
    }

    /**
     * 基础的请求地址
     *
     * @param baseUrl
     * @return
     */
    public OlyHttp setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
        return this;
    }

    public OlyHttp setMuiltUrl(Interceptor... interceptors) {
        this.muiltUrl = interceptors;
        return this;
    }
    public OlyHttp setOkHttpClient(OkHttpClient client) {
        this.okHttpClient = client;
        return this;
    }

    public void build() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (muiltUrl != null && muiltUrl.length > 0) {
            for (Interceptor interceptor : muiltUrl) {
                builder.addInterceptor(interceptor);
            }

        }
        builder.retryOnConnectionFailure(true)
                .readTimeout(timeReadOut, TimeUnit.SECONDS)
                .connectTimeout(timeConnOut, TimeUnit.SECONDS);

        if (okHttpClient == null) {
            okHttpClient = builder.build();
        }
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.serializeNulls(); //这个才是秘密
        Gson gson = gsonBuilder.create();

        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    /**
     * 创建 Service 接口类
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T create(final Class<T> service) {
        return retrofit.create(service);
    }


}